<template>
  <el-card>
    <el-row style="margin-bottom: 20px;">
      <el-col>
        <el-button type="primary" @click="addImg"
        >上传图片</el-button
        >
        <el-button style="margin-left: 100px;" type="success"
        @click="changesort">编辑排序</el-button
        >
      </el-col>
    </el-row>
    <el-table
        row-key="id"
        :data="tableData"
        width="500"
    border>
      <el-table-column
          label="拖拽排序"
          type="index"
          width="150"
      align="center">
      </el-table-column>
      <el-table-column  label="图片" sortable width="250" align="center" header-align="center">
        <template v-slot="scope">
          <el-image style="width: 200px; height: 100px" :src="scope.row.pictureUrl" :preview-src-list="[scope.row.pictureUrl]" :key="scope.row.id">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>

      <el-table-column
          prop="turnUrl"
          label="url地址"
          align="center"
          width="300"
      >
      </el-table-column>
      <el-table-column label="操作"   width="200" align="center">
        <template v-slot="scope">
          <el-button type="warning"  @click="editImg(scope.row)">修改</el-button>
          <el-button type="danger"  @click="deleImg(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
<!--    上传图片弹窗-->
    <el-dialog width="30%" title="上传图片" :visible.sync="addFormVisible" @close="addFormVisibleclose">
      <el-form :model="addFrom">
        <el-form-item label="图片地址" label-width="120px">
          <el-input v-model="addFrom.url" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="图片上传" label-width="120px">
          <div>
            <!-- 图片，用来展示用户选择的头像 -->
         <div  class="the_img"
               v-if="!this.avatar"
               @click="chooseImg"
              >上传图片
         </div>
            <img class="the_img" v-else :src="this.avatar" alt="" />
            <!-- 按钮区域 -->
            <div class="btn-box">
              <input
                  type="file"
                  accept="image/*"
                  style="display: none"
                  ref="iptRef"
                  @change="onFileChange"
              />
            </div>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="uploadFn">确 定</el-button>
      </div>
    </el-dialog>
<!--    修改url弹窗-->
    <el-dialog width="30%" title="修改图片url地址" :visible.sync="Urldialog">
      <el-form :model="Urlform">
        <el-form-item label="url地址" label-width="80px">
          <el-input v-model="Urlform.url" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="Urldialog = false">取 消</el-button>
        <el-button type="primary" @click="UrldialogSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>
<script>
import  Sortable from 'sortablejs'
export default {
  data() {
    return {
      maximg:6,
      Urlform:{
        id:'',
      url:""
      },
      Urldialog:false,
      avatar:'',
      addFrom:{
        url:'',
        imgurl:''
      },
      addFormVisible:false,
      tableData: [
          {
        id:1,
        url: 'www.baidu.com',
        imgurl: 'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fpic.5tu.cn%2Fuploads%2Fallimg%2F1712%2Fpic_5tu_big_201711261848297542.jpg&refer=http%3A%2F%2Fpic.5tu.cn&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1673666983&t=f17069bdc62216df0eb402c252906be7'
      },
      ]
    }
  },
  mounted () {
    // 行拖拽排序
    //   this.rowDrop()
  },
  created() {
    this.getAllImg()
  },

  methods:{

    //获取照片列表
    getAllImg(){
      this.$axios({
        url:"/api/webPublicityColumn/listData",
        method: "GET",
      }).then( res=>{
        console.log(res.data.data);
      this.tableData = res.data.data;
      })
    },
    changesort() {
   this.rowDrop()
    },
    rowDrop () {
        let tbody = document.querySelector('.el-table__body-wrapper tbody')
        let _this = this
        Sortable.create(tbody, {
          // or { name: "...", pull: [true, false, 'clone', array], put: [true, false, array] }
          group: {
            name: 'words',
            pull: true,
            put: true
          },
          animation: 150, // ms, number 单位：ms，定义排序动画的时间
          onAdd: function (evt) { // 拖拽时候添加有新的节点的时候发生该事件
            console.log('onAdd.foo:', [evt.item, evt.from])
          },
          onUpdate: function (evt) { // 拖拽更新节点位置发生该事件
            console.log('onUpdate.foo:', [evt.item, evt.from])
          },
          onRemove: function (evt) { // 删除拖拽节点的时候促发该事件
            console.log('onRemove.foo:', [evt.item, evt.from])
          },
          onStart: function (evt) { // 开始拖拽出发该函数
            console.log('onStart.foo:', [evt.item, evt.from])
          },
          onSort: function (evt) { // 发生排序发生该事件
            console.log('onSort.foo:', [evt.item, evt.from])
          },
          onEnd ({ newIndex, oldIndex }) { // 结束拖拽
            let currRow = _this.tableData.splice(oldIndex, 1)[0]
            _this.tableData.splice(newIndex, 0, currRow)
            console.log(_this.tableData)
          }
        })
    },
    addImg(){
      console.log(this.tableData)
  this.addFormVisible=true
    },
    addFormVisibleclose(){
        this.addFrom={url:'', imgurl:''}
      this.avatar=''
    },
    editImg(e){
        this.Urlform.id=JSON.parse(JSON.stringify(e.id))
      this.Urlform.url=JSON.parse(JSON.stringify(e.turnUrl))
      this.Urldialog=true

    },
    UrldialogSubmit(){
      console.log(this.Urlform)
      this.$axios({
        method: 'POST',
        url: 'api/webPublicityColumn/editTurnUrl',
        params: {
          id: this.Urlform.id,
          turnUrl:this.Urlform.url
        }
      }).then((res) => {
        if (res.data.code == 1) {
          this.$message.success('修改成功');
          this.getAllImg();
        } else {
          this.$message.error('修改失败');

        }

      });
      this.Urldialog=false
    },
    deleImg(row){
      console.log(row)
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
          .then(()=>{
      this.$axios({
        method:'POST',
        url: '/api/webPublicityColumn/delete',
      params: {
          id: row.id
      }

      }).then((res)=>{
        console.log(res)
        if (res.data.code==1){
          this.$message({
            type:'success',
            message: '删除成功!'
          })
          this.getAllImg()
        }
        // this.getAllImg()
      })
          })
          .catch(()=>{
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          })
    },
    chooseImg () {
      // 模拟点击行为
      this.$refs.iptRef.click()
    },
    // async uploadFn () {
    //   const { data: res } = await updateAvatarAPI(this.avatar)
    //   if (res.code !== 0) return this.$message.error('上传头像失败！')
    //   this.$message.success('上传头像成功！')
    //   this.$store.dispatch('initUserInfo')
    // }
    uploadFn(){
    this.addFrom.imgurl=this.avatar
      console.log(this.addFrom)
      this.addFormVisible=false
      if(this.tableData.length>=6){
        this.$message.error('最大上传6张照片')
        return
      }
      this.$axios({
        method: 'post',
        url: '/api/webPublicityColumn/add',
        params: {
          pictureUrl:this.addFrom.imgurl,
          turnUrl:this.addFrom.url
        },
        headers: {
          'Content-type': 'application/json',
        },
      }).then(res => {
     if(res.data.code ==1){
       this.$message.success('上传成功！')
       this.getAllImg()
     }
      })

    },
    onFileChange (e) {
      // 获取用户选择的文件列表（伪数组）
      const files = e.target.files
      if (files.length === 0) {
        // 没有选择图片
        this.avatar = ''
      } else {
        // 选择了图片
        // 1. 创建 FileReader 对象
        const fr = new FileReader()
        // 2. 调用 readAsDataURL 函数，读取文件内容
        fr.readAsDataURL(files[0])
        // 3. 监听 fr 的 onload 事件
        this.avatar = URL.createObjectURL(files[0])
        console.log(this.avatar)

      }
    },

  }
}
</script>
<style lang="scss" scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.the_img {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  text-align: center;
  font-size: 22px;
  line-height: 300px;
  width: 300px;
  height: 300px;
}
</style>
